package com.pkcargo.service.search;

import org.springside.modules.orm.hibernate.DefaultEntityManager;
import org.springside.modules.orm.Page;
import org.springframework.util.Assert;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Order;
import com.pkcargo.entity.search.Metadata;

import java.util.List;

@Service
@Transactional
public class SearchManager extends DefaultEntityManager<Metadata, Long> {
    @SuppressWarnings("unchecked")
    public Page<Metadata> search(Page<Metadata> page, String sql) {
        Assert.hasText(sql, "sql不能为空");
        Query query = entityDao.getSession().createSQLQuery(sql).addEntity(Metadata.class);
        List result = query.list();
        page.setResult(result);
        return page;
    }

    public int countTotal(String countSql) {
        Assert.hasText(countSql, "countsql不能为空");
        Query query = entityDao.getSession().createSQLQuery(countSql).addScalar("c", Hibernate.INTEGER);
        return (Integer) query.uniqueResult();
    }
    @SuppressWarnings("unchecked")
    public List<Metadata> indexList(){
        return entityDao.getSession().createCriteria(Metadata.class)
                .add(Restrictions.eq("valid",true))
                .addOrder(Order.desc("captureTime"))
                .setMaxResults(10)
                .list();
    }
}
